package cn.stylefeng.guns.modular.hx.storage.controller;

import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicPutgoods;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.BasicPutgoodsParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicXlbOauth2tokenParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicPutgoodsResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicPutgoodsService;
import cn.stylefeng.guns.modular.basic.service.BasicWarehouseService;
import cn.stylefeng.guns.modular.basic.service.BasicXlbOauth2tokenService;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoods;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsService;
import cn.stylefeng.guns.modular.hx.order.utils.EmojiTransferUtil;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageOut;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageOutDetailed;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageStock;
import cn.stylefeng.guns.modular.hx.storage.mapper.HxStorageStockMapper;
import cn.stylefeng.guns.modular.hx.storage.model.dto.ManagePageContentDetailDTO;
import cn.stylefeng.guns.modular.hx.storage.model.dto.ManagePageContentDTO;
import cn.stylefeng.guns.modular.hx.storage.model.dto.ManagePageDTO;
import cn.stylefeng.guns.modular.hx.storage.model.dto.ManageReadDetailDTO;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageManageParams;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageOutDetailedParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageOutParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageStockParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.ConversionResult;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStorageOutResult;
import cn.stylefeng.guns.modular.hx.storage.model.vo.ManageAuditVO;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageOutDetailedService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageOutService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageStockService;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author : like
 * @date : 2024/8/13 19:23
 * @Version: 1.0
 */
@Slf4j
@Controller
@RequestMapping("/hxStorageManage")
public class HxStorageManageController extends BaseController {
    private String PREFIX = "/hx/storage/hxStorageManage";

    private static final String XLB_MANAGE_PAGE = "https://test-api.xlbsoft.com/api/hxl.open.wms.outorder.page"; // 分页

    private static final String XLB_MANAGE_READ = "https://test-api.xlbsoft.com/api/hxl.open.wms.outorder.read"; // 读取

    private static final String XLB_MANAGE_AUDIT = "https://test-api.xlbsoft.com/api/hxl.open.wms.outorder.audit"; // 审核

    @Autowired
    private UserService userService;

    @Autowired
    private BasicWarehouseService basicWarehouseService;

    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private HxStorageOutService hxStorageOutService;

    @Autowired
    private BasicPutgoodsService basicPutgoodsService;

    @Autowired
    private HxStorageOutDetailedService hxStorageOutDetailedService;

    @Autowired
    private HxStorageStockService hxStorageStockService;

    @Autowired
    private HxStorageStockMapper hxStorageStockMapper;

    @Autowired
    private HxBasicGoodsService hxBasicGoodsService;

    @Autowired
    private BasicXlbOauth2tokenService basicXlbOauth2tokenService;

    @Resource
    private DeptService deptService;


    /**
     * 首页
     *
     * @param model
     * @return
     */
    @RequestMapping("")
    public String index(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/hxStorageManage.html";
    }


    /**
     * 添加出库单页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/add")
    public String add(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));

        BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
        basicPutgoodsParam.setUnitCategory("发货");
        basicPutgoodsParam.setUnitType("配送中心");
        basicPutgoodsParam.setDeptId(deptId);
        List<BasicPutgoodsResult> pglist = basicPutgoodsService.findListBySpec(basicPutgoodsParam, user.getOperateId());
        model.addAttribute("pglist", pglist);
        return PREFIX + "/hxStorageManage_add.html";
    }

    /**
     * 添加详情页面
     *
     * @param storageNumber
     * @param model
     * @return
     */
    @RequestMapping("/add2")
    public String add(@RequestParam("storageNumber") String storageNumber, Model model) {
        model.addAttribute("storageNumber", storageNumber);
        return PREFIX + "/hxStorageManageDetailed_add.html";
    }

    /**
     * 选择库位
     * @return
     */
    @RequestMapping("tochoiceStorageStock")
    public String tochoiceStorageStock() {
        return PREFIX + "/choiceStorageStock.html";
    }

    /**
     * 选择库位列表
     * @param hxStorageStockParam
     * @param condition
     * @return
     */
    @ResponseBody
    @RequestMapping("/choicelist")
    public LayuiPageInfo choicelist(HxStorageStockParam hxStorageStockParam, String condition) {
        User user = userService.getcurrentUser();
        hxStorageStockParam.setOperateId(user.getOperateId());
        hxStorageStockParam.setDeptId(user.getDeptId());
        return this.hxStorageStockService.findchoicePageBySpec2(hxStorageStockParam,condition);
    }

    /**
     * 选择商品页面
     * @param model
     * @return
     */
    @RequestMapping("toChoiceGoods_od")
    public String toChoiceGoods_od(Model model) {
        User user = userService.getcurrentUser();
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/choiceGoodsOd.html";
    }

    /**
     * 拉取新零帮出库单页面
     */
    @RequestMapping("/pullXlbOutStorageManage")
    public String pullXlbOutStorageManage(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        // 客户列表
        model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));

        // 仓库列表
        model.addAttribute("wlist", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));

        // 发货单位
        BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
        basicPutgoodsParam.setUnitCategory("发货");
        basicPutgoodsParam.setUnitType("配送中心");
        basicPutgoodsParam.setDeptId(deptId);
        List<BasicPutgoodsResult> pglist = basicPutgoodsService.findListBySpec(basicPutgoodsParam, user.getOperateId());
        model.addAttribute("pglist", pglist);
        return PREFIX + "/pullXlbOutStorageManage.html";
    }


    /**
     * 查询出库单详情
     *
     * @param hxStorageOutParam
     * @param condition
     * @param startTime
     * @param endTime
     * @param startTime2
     * @param endTime2
     * @return
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(HxStorageOutParam hxStorageOutParam, String condition, String startTime, String endTime, String startTime2, String endTime2) {
        User user = userService.getcurrentUser();
        hxStorageOutParam.setDeptId(user.getDeptId());
        if (ToolUtil.isEmpty(hxStorageOutParam.getTimeType())) {
            hxStorageOutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxStorageOutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxStorageOutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        if (ToolUtil.isNotEmpty(startTime2) && ToolUtil.isNotEmpty(endTime2)) {
            hxStorageOutParam.setTimeInterval2("'" + startTime2 + "' and '" + endTime2 + "'");
        }
        return hxStorageOutService.findPageBySpec2(hxStorageOutParam, condition, user.getOperateId());
    }

    /**
     * 导出
     */
    @ResponseBody
    @RequestMapping("/listAll")
    public List<HxStorageOutResult> listAll(HxStorageOutParam hxStorageOutParam , String condition , String startTime, String endTime,String startTime2,String endTime2) {
        User user = userService.getcurrentUser();
        hxStorageOutParam.setDeptId(user.getDeptId());
        hxStorageOutParam.setDeliverId(user.getDeliverId());
        if(ToolUtil.isEmpty(hxStorageOutParam.getTimeType())) {
            hxStorageOutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxStorageOutParam.setTimeInterval("'"+startTime+"' and '"+endTime+"'");
        } else if (startTime == null && endTime == null){
            hxStorageOutParam.setTimeInterval("'"+DateUtil.getDate()+"' and '"+DateUtil.getDate()+"'");
        }
        if (ToolUtil.isNotEmpty(startTime2) && ToolUtil.isNotEmpty(endTime2)) {
            hxStorageOutParam.setTimeInterval2("'"+startTime2+"' and '"+endTime2+"'");
        }
        return this.hxStorageOutService.findlistAllBySpec2(hxStorageOutParam,condition,user.getOperateId());
    }

    /**
     * 合计
     * @param hxStorageOutParam
     * @param condition
     * @param startTime
     * @param endTime
     * @param startTime2
     * @param endTime2
     * @return
     */
    @ResponseBody
    @RequestMapping("/count")
    public ResponseData count(HxStorageOutParam hxStorageOutParam , String condition , String startTime, String endTime,String startTime2,String endTime2) {
        User user = userService.getcurrentUser();
        hxStorageOutParam.setDeptId(user.getDeptId());
        hxStorageOutParam.setDeliverId(user.getDeliverId());
        if(ToolUtil.isEmpty(hxStorageOutParam.getTimeType())) {
            hxStorageOutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxStorageOutParam.setTimeInterval("'"+startTime+"' and '"+endTime+"'");
        } else if (startTime == null && endTime == null){
            hxStorageOutParam.setTimeInterval("'"+DateUtil.getDate()+"' and '"+DateUtil.getDate()+"'");
        }
        if (ToolUtil.isNotEmpty(startTime2) && ToolUtil.isNotEmpty(endTime2)) {
            hxStorageOutParam.setTimeInterval2("'"+startTime2+"' and '"+endTime2+"'");
        }
        HxStorageOutResult res = this.hxStorageOutService.count2(hxStorageOutParam,condition,user.getOperateId());
        return ResponseData.success(res);
    }

    /**
     * 添加拣货单  单据状态为 ----- 制单
     *
     * @param hxStorageOutParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/addItem")
    @Transactional(rollbackFor = Exception.class,propagation= Propagation.REQUIRED,timeout=120)
    public ResponseData addStorage(HxStorageOutParam hxStorageOutParam) {
        User user = userService.getcurrentUser();
        String trayCode = getOperateIdOrderPrefix(user);
        String storageNumber = null;
        if (ToolUtil.isNotEmpty(hxStorageOutParam.getStorageNumber())) {
            //校验客户单号 是否存在
            if (this.hxStorageOutService.checkCustomerStorage(hxStorageOutParam.getStorageNumber())) {
                return ResponseData.error("单号已存在");
            }
        } else {
            storageNumber = trayCode + "CK" + DateUtil.getDatesBch() + DateUtil.getRandomNumber();
            hxStorageOutParam.setStorageNumber(storageNumber);
        }
        Object WarehouseId = hxStorageOutParam.getSetWarehouseId();
        if (WarehouseId != null) {
            BasicWarehouse bawBasicWarehouse = basicWarehouseService.getById(Integer.parseInt(WarehouseId.toString()));
            hxStorageOutParam.setSetWarehouse(bawBasicWarehouse.getWarehouseName());//set 仓库名称
        }
        Object CustomerId = hxStorageOutParam.getCustomerId();
        if (CustomerId != null) {
            BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(CustomerId.toString()));
            hxStorageOutParam.setCustomerName(basicCustomer.getCustomerName());//set 客户名称
        }
        Object setUnitId = hxStorageOutParam.getSetUnitId();
        if (setUnitId != null) {
            BasicPutgoods basicPutgoods = basicPutgoodsService.getById(Integer.parseInt(setUnitId.toString()));
            hxStorageOutParam.setSetUnit(basicPutgoods.getPutgoodsName());
        }
        hxStorageOutParam.setDeptId(user.getDeptId());
        hxStorageOutParam.setDeliverId(user.getDeliverId());
        //
        hxStorageOutParam.setStorageState("制单");//set 单据状态
        hxStorageOutParam.setCreateUserName(user.getName());//set 制单用户名称
        hxStorageOutService.add(hxStorageOutParam);
        // 获取id
        HxStorageOut storageNumber1 = hxStorageOutService.getBaseMapper().selectOne(new QueryWrapper<HxStorageOut>().eq("storage_number", storageNumber));
        hxStorageOutParam.setId(storageNumber1.getId());
        return ResponseData.success(hxStorageOutParam);
    }


    /**
     * 添加拣货单详情
     *
     * @param hxStorageOutDetailedParam
     * @return
     */
    @RequestMapping("/addDetailedItem")
    @ResponseBody
    public ResponseData addDetailedItem(HxStorageOutDetailedParam hxStorageOutDetailedParam) {
        String goodsName = hxStorageOutDetailedParam.getGoodsName();
        //解决参数中的 英文括号
        if (goodsName != null && goodsName != "") {
            goodsName = goodsName.replace("& #40;", "(");
            goodsName = goodsName.replace("& #41;", ")");
            hxStorageOutDetailedParam.setGoodsName(goodsName);
        }
        // 判断商品详情是否重复
        String storageNumber = hxStorageOutDetailedParam.getStorageNumber();
        Long goodsId = hxStorageOutDetailedParam.getGoodsId();
        List<HxStorageOutDetailed> existingRecord = hxStorageOutDetailedService.lambdaQuery()
                .select(HxStorageOutDetailed::getId, HxStorageOutDetailed::getStorageNumber, HxStorageOutDetailed::getGoodsId)
                .eq(HxStorageOutDetailed::getStorageNumber, storageNumber)
                .eq(HxStorageOutDetailed::getGoodsId, goodsId)
                .list();

        if (!existingRecord.isEmpty()) {
            return ResponseData.error("该商品详情已存在，请勿重复添加");
        }
        hxStorageOutDetailedService.add(hxStorageOutDetailedParam);
        return ResponseData.success(200, "添加成功", "");
    }

    /**
     * 编辑拣货单详情 并且判断库位，计算体积重量
     *
     *              * 计算出库的长宽高，价格 ==== 根据采购单位换算
     *              * 采购数量 = 基本数量 * 采购换数率
     *              * 基本数量体积 = 采购体积 / 采购换数率
     *              * 基本数量重量 = 采购重量 / 采购换数率
     *              * 基本配送价格 = 配送价格 / 配送换数率
     *              *
     * @param hxStorageOutDetailedParam
     * @return
     */
    @RequestMapping("/editItem")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class,propagation= Propagation.REQUIRED,timeout=120)
    public ResponseData editItem(HxStorageOutDetailedParam hxStorageOutDetailedParam) {
        User user = userService.getcurrentUser();
        Long operateId = user.getOperateId();
        Long deptId = user.getDeptId();
        String storageNumber = hxStorageOutDetailedParam.getStorageNumber();

        // 检查订单状态
        HxStorageOut storageNumber1 = hxStorageOutService.getBaseMapper()
                .selectOne(new QueryWrapper<HxStorageOut>()
                        .eq("storage_number", storageNumber)
                        .eq("dept_id", deptId));

        if ("审核".equals(storageNumber1.getStorageState())) {
            return ResponseData.error("订单号:" + storageNumber1.getStorageNumber() + " 已审核，不允许修改。");
        }

        String goodsName = hxStorageOutDetailedParam.getGoodsName();
        // 解决参数中的英文括号
        if (goodsName != null && !goodsName.isEmpty()) {
            goodsName = goodsName.replace("& #40;", "(");
            goodsName = goodsName.replace("& #41;", ")");
            hxStorageOutDetailedParam.setGoodsName(goodsName);
        }

        // 判断使用参数
        Long goodsId = hxStorageOutDetailedParam.getGoodsId();
        String positionNumber = hxStorageOutDetailedParam.getPositionNumber();

        // 传入数量计算出库的长宽高，价格
        String num = hxStorageOutDetailedParam.getNum(); // 数量
        String unit = hxStorageOutDetailedParam.getUnit(); // 单位
        BigDecimal presentQuantity = hxStorageOutDetailedParam.getPresentQuantity(); // 赠品数量
        String presentUnit = hxStorageOutDetailedParam.getPresentUnit(); // 赠品单位

        if (
                (num != null && !num.isEmpty()) ||
                (presentQuantity != null && !presentQuantity.equals(BigDecimal.ZERO)) ||
                (unit != null && !unit.isEmpty())
        ) {

            log.info("goodsId:{}" , goodsId);

            if ((num != null && !num.isEmpty()) && (unit == null || unit.trim().isEmpty())) {
                return ResponseData.error("请输入单位");
            }
            if ((presentQuantity != null && !presentQuantity.equals(BigDecimal.ZERO)) && (presentUnit == null || presentUnit.trim().isEmpty())) {
                return ResponseData.error("请先输入赠品单位");
            }

            // 1、计算基本数量
            HxStorageOutDetailed hxStorageOutDetailed = new HxStorageOutDetailed();
            hxStorageOutDetailed.setNum(num);
            hxStorageOutDetailed.setUnit(unit);
            hxStorageOutDetailed.setPresentQuantity(presentQuantity);
            hxStorageOutDetailed.setPresentUnit(presentUnit);

            ConversionResult conversionResult = null;
            try { // 捕获异常
                conversionResult = this.convertUnitsAndCheckStock(hxStorageOutDetailed, goodsId, deptId);
            } catch (RuntimeException e) {
                log.error("计算换算失败：{}" , e.getMessage());
                return ResponseData.error(e.getMessage());
            }

            BigDecimal convertedNum = conversionResult.getConvertedNum(); // 基本总数量

            // 2、获取商品信息计算出库提交
            HxBasicGoods rates = hxBasicGoodsService.getBaseMapper().selectOne(new QueryWrapper<HxBasicGoods>()
                    .eq("id", goodsId)
                    .eq("dept_id", deptId));
            if (rates == null) {
                throw new RuntimeException("商品ID:" + goodsId + " 的换算率未设置。");
            }
            BigDecimal goodsVolume = new BigDecimal(rates.getGoodsVolume()); // 采购重量
            BigDecimal goodsWeight = new BigDecimal(rates.getGoodsWeight()); // 采购体积
            BigDecimal cgRate = new BigDecimal(rates.getCgRate()); // 采购换数率
            BigDecimal psRate = new BigDecimal(rates.getPsRate()); // 配送换数率
            BigDecimal goodsChargingPs = new BigDecimal(rates.getGoodsChargingPs()); // 配送价格

            // 检查除数是否为零
            if (cgRate.compareTo(BigDecimal.ZERO) == 0) {
                return ResponseData.error("错误：除数不能为零");
            }

            // 计算结果
            BigDecimal resultVolume = goodsVolume.divide(cgRate, 5, RoundingMode.HALF_UP); // 基本体积
            BigDecimal resultWeight = goodsWeight.divide(cgRate, 5, RoundingMode.HALF_UP); // 基本重量
            BigDecimal resultMoney = goodsChargingPs.divide(psRate, 5, RoundingMode.HALF_UP); // 基本配送价格

            // 3. 基本数量 * 基本单位体积/重量/金额
            BigDecimal outVolume = resultVolume.multiply(convertedNum);
            BigDecimal outWeight = resultWeight.multiply(convertedNum);
            BigDecimal outMoney = resultMoney.multiply(convertedNum);

            hxStorageOutDetailedParam.setOutVolume(outVolume.toString());
            hxStorageOutDetailedParam.setOutWeight(outWeight.toString());
            hxStorageOutDetailedParam.setOutMoney(outMoney.toString());

            // 4.换算率
            Map<String, BigDecimal> rateMap = new HashMap<>();
            rateMap.put(rates.getJibenUnit(), BigDecimal.ONE);
            rateMap.put(rates.getKcUnit(), new BigDecimal(rates.getKcRate()));
            rateMap.put(rates.getCgUnit(), new BigDecimal(rates.getCgRate()));
            rateMap.put(rates.getPfUnit(), new BigDecimal(rates.getPfRate()));
            rateMap.put(rates.getPsUnit(), new BigDecimal(rates.getPsRate()));

            // 计算基本数量
            BigDecimal rate = rateMap.get(unit);
            BigDecimal jbenNum = BigDecimal.ZERO;
            if (num != null) {
                jbenNum = rate.multiply(new BigDecimal(num));
                hxStorageOutDetailedParam.setJibenNum(String.valueOf(jbenNum)); // 基本数量
            }
            hxStorageOutDetailedParam.setRate(String.valueOf(rate)); // 换算率

            // 计算赠送数量
            BigDecimal rate2 = rateMap.get(presentUnit); // 赠品换算率
            BigDecimal basicPresentQuantity = BigDecimal.ZERO;
            if (hxStorageOutDetailedParam.getPresentQuantity() != null){
                basicPresentQuantity = rate2.multiply(presentQuantity);
                hxStorageOutDetailedParam.setBasicPresentQuantity(basicPresentQuantity); // 赠品基本数量
            }
            hxStorageOutDetailedParam.setPresentRatio(rate2); // 赠品换算率
        }

        // 传入库位，校验商品是否为该库位的商品
        if (positionNumber != null) {
            boolean isMatch = false;
            List<HxStorageStock> positionList = hxStorageStockMapper
                    .selectList(new QueryWrapper<HxStorageStock>()
                            .eq("goods_id", goodsId)
                            .eq("operate_id", operateId)
                            .eq("dept_id", deptId)
                            .orderByAsc("jiben_num"));
            if(positionList == null || positionList.isEmpty()){
                log.info("库位：{}" , positionNumber + " 不存在该商品。");
                return ResponseData.error("库位" + positionNumber + " 不存在该商品。");
            }

            for (HxStorageStock stock : positionList) {
                if (stock.getPositionNumber().equals(positionNumber)) {
                    isMatch = true;

                    // 更新拣货单详情参数
                    hxStorageOutDetailedParam.setPositionNumber(stock.getPositionNumber());
                    hxStorageOutDetailedParam.setPositionId(stock.getPositionId());
                    hxStorageOutDetailedParam.setJibenUnit(stock.getJibenUnit());
//                    hxStorageOutDetailedParam.setUnit(stock.getJibenUnit());
//                    hxStorageOutDetailedParam.setPresentUnit(stock.getJibenUnit());
                    hxStorageOutDetailedParam.setDetailedDate(stock.getDetailedDate());
                    hxStorageOutDetailedParam.setPositionId(stock.getPositionId());
                    hxStorageOutDetailedParam.setStockId(Long.valueOf(stock.getId()));
                    hxStorageOutDetailedParam.setTrayNumber(stock.getTrayNumber());
                    hxStorageOutDetailedParam.setGoodsWeight(stock.getGoodsWeight());
                    hxStorageOutDetailedParam.setGoodsVolume(stock.getGoodsVolume());
                    hxStorageOutDetailedParam.setBasicPositionQuantity(stock.getJibenNum());

                    // 设置到期时间
                    String productionDateString = stock.getDetailedDate();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date productionDate = sdf.parse(productionDateString);
                        String goodsWarranty = stock.getGoodsWarranty(); // 保质期单位月
                        int warrantyMonths = Integer.parseInt(goodsWarranty);
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(productionDate);
                        calendar.add(Calendar.MONTH, warrantyMonths); // 添加保质期的月数
                        Date expiryDate = calendar.getTime();
                        hxStorageOutDetailedParam.setDaoqiDate(sdf.format(expiryDate));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (!isMatch) {
                return ResponseData.error("库位与商品不匹配");
            }
        }

        // 更新拣货单详情
        hxStorageOutDetailedService.update(hxStorageOutDetailedParam);
        return ResponseData.success(201, "编辑成功", "");
    }


    /**
     * 拣货单审核功能实现说明：
     * <p>
     * 1. 扣减基本单位库存。
     * 2. 选择单位，包括基本单位、库存单位、采购单位、批发单位和配送单位。
     * 3. 选择基本单位时，直接扣减。
     * 4. 选择库存单位时，扣减数量乘以库存换算率（num * kcRate）。
     * 5. 选择采购单位时，扣减数量乘以采购换算率（num * cgRate）。
     * 6. 选择批发单位时，扣减数量乘以批发换算率（num * pfRate）。
     * 7. 选择配送单位时，扣减数量乘以配送换算率（num * psRate）。
     * </p>
     * <p>
     * 拣货单审核步骤：
     * <ol>
     *     <li>根据id查询订单号，根据订单号获取拣货详情。</li>
     *     <li>遍历拣货单详情，盘点库位库存，判断是否充足。</li>
     *     <li>换算单位，使用map代替if逻辑。</li>
     *     <li>验证并扣减库位库存。
     *         <ul>
     *             <li>outNum - 前端传的出库数量，未进行单位转换。</li>
     *             <li>convertedNum - 换算成基本单位后需要出库的数量。</li>
     *             <li>countNum - 库位库存的当前数量（多条数据累加）。</li>
     *         </ul>
     *     </li>
     *     <li>删除逻辑：
     *         <ol>
     *             <li>删除对应库位库存中数量多的记录。</li>
     *             <li>如果基本数量减去出库基本数量后不为0，则修改记录的基本数量。</li>
     *             <li>如果减完后为0，则删除该记录。</li>
     *             <li>如果减完后为负数，删除该记录，并记录负数值，用下一条记录的剩余数量继续出库。</li>
     *         </ol>
     *     </li>
     *     <li>根据id修改状态为审核（暂未对接新零帮）。</li>
     * </ol>
     * </p>
     *
     * @param ids 拣货单ID列表
     * @return 操作结果
     */
    @Transactional(rollbackFor = Exception.class,propagation= Propagation.REQUIRED,timeout=120)
    @ResponseBody
    @RequestMapping("/finish")
    public ResponseData btnFinish(@RequestParam("ids") Long[] ids) {
        if (ids == null || ids.length == 0){
            return ResponseData.error("请选择订单");
        }
        try {
            User user = userService.getcurrentUser();
            Long operateId = user.getOperateId();
            Long deptId = user.getDeptId();

            for (Long id : ids) {
                HxStorageOut hxStorageOut = hxStorageOutService.getById(id);
                if ("审核".equals(hxStorageOut.getStorageState())) {
                    return ResponseData.error("订单号:" + hxStorageOut.getStorageNumber() + " 已审核，请检查是否选择正确。");
                }

                // 1、根据id查询订单号，根据订单号获取拣货详情
                String storageNumber = hxStorageOut.getStorageNumber();
                QueryWrapper<HxStorageOutDetailed> storageNumberDetailed =
                        new QueryWrapper<HxStorageOutDetailed>()
                                .eq("storage_number", storageNumber);
                List<HxStorageOutDetailed> hxStorageOutDetaileds = hxStorageOutDetailedService.getBaseMapper().selectList(storageNumberDetailed);
                if (hxStorageOutDetaileds == null || hxStorageOutDetaileds.isEmpty()){
                    return ResponseData.error("订单号:" + storageNumber + " 中不存在拣货详情，请检查是否选择正确。");
                }

                ManageAuditVO manageAuditVO = new ManageAuditVO(); // 拣货单信息(新零帮)
                List<ManageAuditVO.DetailDTO> details = new ArrayList<>(); // 拣货单详情信息(新零帮)

                // 2.遍历拣货单详情，盘点库位库存，是否充足
                for (HxStorageOutDetailed hxStorageOutDetailed : hxStorageOutDetaileds) {
                    if (hxStorageOutDetailed.getNum() == null || hxStorageOutDetailed.getNum().trim().isEmpty() || hxStorageOutDetailed.getPositionNumber() == null || hxStorageOutDetailed.getPositionNumber().trim().isEmpty()) {
                        return ResponseData.error("订单号:" + storageNumber + " 中存在明细数据未填写完整，请检查数量和库位是否已正确填写。");
                    } // 判断库位和数量不为空
                    Long goodsId = hxStorageOutDetailed.getGoodsId();

                    // 3、换算单位
                    ConversionResult conversionResult = null;
                    try { // 捕获异常
                        conversionResult = this.convertUnitsAndCheckStock(hxStorageOutDetailed, goodsId, deptId);
                    } catch (RuntimeException e) {
                        log.error("计算换算失败：{}" , e.getMessage());
                        return ResponseData.error(e.getMessage());
                    }
                    BigDecimal convertedNum = conversionResult.getConvertedNum(); // 扣除的基本数量
                    BigDecimal countNum = BigDecimal.ZERO; // 计算库位库存

                    // 4、验证时间库位库存 扣除极鹿库位库存
                    try {
                        this.checkStock(hxStorageOutDetailed, convertedNum, countNum, operateId, goodsId, deptId);
                    }catch (RuntimeException e){
                        log.error("验证库位库存失败：{}" , e.getMessage());
                        return ResponseData.error(e.getMessage());
                    }

                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String outTime = dateFormat.format(new Date());
                    hxStorageOutDetailed.setV2(outTime); // 设置出库时间 暂用v2
                    hxStorageOutDetailedService.updateById(hxStorageOutDetailed);

                    // 封装新零帮拣货详情
                    ManageAuditVO.DetailDTO detail = new ManageAuditVO.DetailDTO();
                    detail.setQuantity(hxStorageOutDetailed.getNum()); // 数量
                    detail.setUnit(hxStorageOutDetailed.getUnit()); // 单位
                    detail.setRatio(hxStorageOutDetailed.getRate()); // 换算率
                    detail.setBasicQuantity(hxStorageOutDetailed.getJibenNum()); // 基本数量
                    detail.setBasicUnit(hxStorageOutDetailed.getJibenUnit()); // 基本单位
                    detail.setPresentQuantity(hxStorageOutDetailed.getPresentQuantity()); // 赠品数量
                    detail.setPresentRatio(hxStorageOutDetailed.getPresentRatio()); // 赠品换算率
                    detail.setPresentUnit(hxStorageOutDetailed.getPresentUnit()); // 赠品单位
                    detail.setBasicPresentQuantity(hxStorageOutDetailed.getBasicPresentQuantity()); // 赠品基本数量
                    detail.setItemCode(hxStorageOutDetailed.getGoodsNumber()); // 商品代码
                    detail.setItemId(hxStorageOutDetailed.getGoodsId()); // 商品id
                    detail.setItemName(hxStorageOutDetailed.getGoodsName()); // 商品名称
                    details.add(detail);
                }
                manageAuditVO.setDetails(details); // set 详情

                log.info("新零帮审核VO：{}" , manageAuditVO);

                // 根据客户管理做出限制
                Long customerDeptId = hxStorageOut.getDeptId();
                BasicCustomer one = basicCustomerService.lambdaQuery()
                        .select(BasicCustomer::getId, BasicCustomer::getModeTms, BasicCustomer::getDeptId)
                        .eq(BasicCustomer::getDeptId, customerDeptId)
                        .one();
                String modeTms = one.getModeTms();
                if (Objects.equals(modeTms, String.valueOf(3))){
                    try { // 新零帮审核
                        ResponseData responseData = this.btnFinishXlb(manageAuditVO, hxStorageOut);
                        if (responseData.getCode() != 200){
                            return ResponseData.error(responseData.getMessage());
                        }
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException("新零帮审核异常:{}" , e);
                    }
                }

                // 6、根据id，修改状态为审核
                if ("制单".equals(hxStorageOut.getStorageState())) {
                    HxStorageOutParam param = new HxStorageOutParam();
                    param.setStorageState("审核");
                    param.setId(Integer.parseInt(id.toString()));
                    hxStorageOutService.update(param);
                }
            }
            return ResponseData.success(202, "审核成功", "");
        } catch (Exception e) {
            log.error("出库单审核出现异常: {}", e.getMessage(), e);
            return ResponseData.error("出库单审核出现异常:" + e.getMessage());
        }
    }

    /**
     * 出库单批量作废
     *
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("/toVoid")
    @ResponseBody
    public ResponseData toVoid(@RequestParam("ids") Long[] ids) {
        for (Long id : ids) {
            HxStorageOut hxStorageOut = hxStorageOutService.getById(id);
            if (hxStorageOut.getStorageState().equals("制单")) {
                HxStorageOutParam param = new HxStorageOutParam();
                param.setStorageState("作废");
                param.setId(Integer.parseInt(id.toString()));
                hxStorageOutService.update(param);
            }
        }
        return ResponseData.success(203, "作废成功", "");
    }

    /***********************************************新零帮************************************************************/


    /**
     * 拉取新零帮出库单列表 测试方法
     *
     * @param hxStorageManageParams
     * @return
     */
    @Transactional(rollbackFor = Exception.class,propagation= Propagation.REQUIRED,timeout=120)
    @ResponseBody
    @RequestMapping("/pullXlbOutStorageManageList")
    public ResponseData pullXlbOutStorageManageList(HxStorageManageParams hxStorageManageParams) throws IOException {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();

        // 根据客户管理做出限制
        BasicCustomer one = basicCustomerService.lambdaQuery()
                .select(BasicCustomer::getId, BasicCustomer::getModeTms, BasicCustomer::getDeptId)
                .eq(BasicCustomer::getDeptId, deptId)
                .one();
        String modeTms = one.getModeTms();
        if (modeTms == null || !modeTms.equals("3")){
            return ResponseData.error("管理员设置不允许拉取！");
        }

        // 1、获取公司号，拿XLB的oauth2TOKEN
        BasicCustomer basicCustomerList = basicCustomerService.getById(hxStorageManageParams.getCustomerId());
        if (basicCustomerList == null) {
            return ResponseData.error("请维护公司号");
        }
        String gsnumber = basicCustomerList.getGsnumber();
        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setGsnumber(gsnumber);
        BasicXlbOauth2tokenResult bySpec = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
        String oauth2TokenXlb = bySpec.getOauth2TokenXlb();

        // 2、封装请求
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + oauth2TokenXlb);

        // 请求数据
        // 1.新零帮门店id
        String storeIdXlb = basicCustomerList.getStoreIdXlb();

        // 2.新零帮仓库id
        BasicWarehouse BasicWarehouseList = basicWarehouseService.getById(hxStorageManageParams.getSetWarehouseId());
        String warehouseXlbId = BasicWarehouseList.getWarehouseXlbId();

        // 3.创建时间
        List<String> createDate = new ArrayList<>();
        createDate.add(hxStorageManageParams.getModified_begin());
        createDate.add(hxStorageManageParams.getModified_end());

        // 4.客户号集合
        String getUnitId = hxStorageManageParams.getGetUnitId();
        String[] clientIdsArray = null;
        if (getUnitId != null){
            clientIdsArray = getUnitId.split(",");
            // 过滤掉空字符串
            clientIdsArray = Arrays.stream(clientIdsArray)
                    .filter(client -> !client.isEmpty())
                    .toArray(String[]::new);
        }

        // 5.订单类型
        String orderType = hxStorageManageParams.getOrderType();

        // 6.排序属性
        JSONArray ordersArray = new JSONArray();
        JSONObject orderObject = new JSONObject();
        orderObject.put("direction", "DESC");
        orderObject.put("property", "fid");
        // 将订单对象添加到订单数组中
        ordersArray.put(orderObject);

        // 7.分页
        String pageNumber = "0";
        String pageSize = "200";

        // 请求体
        JSONObject body = new JSONObject();
        body.put("store_id", storeIdXlb);
        body.put("storehouse_id", warehouseXlbId);
        body.put("client_ids", clientIdsArray);
        body.put("create_date", createDate);
        body.put("order_type", orderType);
        body.put("orders", ordersArray);
        body.put("page_number", pageNumber);
        body.put("page_size", pageSize);

        log.info("拣货单请求参数：{}" , body);

        // 发送请求
        String post = HttpRequest.post(XLB_MANAGE_PAGE)
                .header(headers)
                .body(body.toString()).execute().body();

        log.info("拣货单请求结果：{}" , post);

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            ManagePageDTO managePageDTO = objectMapper.readValue(post, ManagePageDTO.class);
            List<ManagePageContentDTO> content = managePageDTO.getData().getContent();

            for (ManagePageContentDTO managePageContentDTO : content) {
                String fid = managePageContentDTO.getFid();
                HxStorageOutParam hxStorageOut = new HxStorageOutParam();

                String memo = (managePageContentDTO.getAdjustReasonName() != null ? managePageContentDTO.getAdjustReasonName() : "") +
                        (managePageContentDTO.getMemo() != null ? managePageContentDTO.getMemo() : "") +
                        (managePageContentDTO.getSystemMemo() != null ? managePageContentDTO.getSystemMemo() : "");
                String notes = EmojiTransferUtil.emojiEncode(memo);
                hxStorageOut.setNotes(notes); // 调整原因

                // 共享属性
                hxStorageOut.setCustomerId(managePageContentDTO.getStoreId()); // 门店id
                hxStorageOut.setCustomerName(managePageContentDTO.getStoreName()); // 门店名称
                hxStorageOut.setCreateUserName(managePageContentDTO.getCreateBy()); // 制单人
                hxStorageOut.setCreateTime(managePageContentDTO.getCreateTime()); // 制单时间
                hxStorageOut.setPeisongTime(managePageContentDTO.getDeliveryDate()); // 配送日
                hxStorageOut.setStorageNumber(fid); // 单据号
                hxStorageOut.setGoodsNum(String.valueOf(managePageContentDTO.getItemCount())); // 商品数量
                hxStorageOut.setOrderType(managePageContentDTO.getOrderTypeName()); // 单据类型名称
                hxStorageOut.setAssociationOrder(managePageContentDTO.getOutApplicationOrderFid()); // 关联出库单
                hxStorageOut.setGoodsNum(String.valueOf(managePageContentDTO.getQuantity())); // 商品数量
                hxStorageOut.setStorageState(managePageContentDTO.getStateName()); // 状态名称
                hxStorageOut.setGetUnitId(managePageContentDTO.getClientId()); // 收货客户id
                hxStorageOut.setGetUnit(managePageContentDTO.getClientName()); // 收货客户姓名
                hxStorageOut.setSetWarehouseId(managePageContentDTO.getStorehouseId()); // 发货仓库id
                hxStorageOut.setSetWarehouse(managePageContentDTO.getStorehouseName()); // 仓库名称

                // 发送请求添加拣货单
                ResponseData responseData = this.addItem(hxStorageOut);
                if (!responseData.getSuccess()) {
                    return ResponseData.error("添加出库单失败！");
                }

                // 构造请求体，请求拣货单详情
                JSONObject bodyDetails = new JSONObject();
                bodyDetails.put("fid", fid);

                log.info("拣货单详情请求参数:{}" , bodyDetails);

                // 发送请求获取拣货单详情
                String postDetails = HttpRequest.post(XLB_MANAGE_READ)
                        .header(headers)
                        .body(bodyDetails.toString()).execute().body();

                log.info("拣货单详情请求结果:{}" , postDetails);

                // 解析拣货单详情
                ManageReadDetailDTO detailResDTO = objectMapper.readValue(postDetails, ManageReadDetailDTO.class);
                List<ManagePageContentDetailDTO> detailContent = detailResDTO.getData().getDetails();

                for (ManagePageContentDetailDTO managePageContentDetailDTO : detailContent) {
                    HxStorageOutDetailedParam hxStorageOutDetailed = new HxStorageOutDetailedParam();

                    // 共享属性
                    hxStorageOutDetailed.setStorageNumber(fid); // 拣货单号

                    // 设置其他属性
                    hxStorageOutDetailed.setUnit(managePageContentDetailDTO.getUnit()); // 单位
                    hxStorageOutDetailed.setNum(String.valueOf(managePageContentDetailDTO.getQuantity())); // 数量
                    hxStorageOutDetailed.setRate(String.valueOf(managePageContentDetailDTO.getRatio())); // 换算率
                    hxStorageOutDetailed.setPresentQuantity(BigDecimal.valueOf(managePageContentDetailDTO.getPresentQuantity())); // 赠送数量
                    if(managePageContentDetailDTO.getPresentRatio() != null){
                        hxStorageOutDetailed.setPresentRatio(BigDecimal.valueOf(managePageContentDetailDTO.getPresentRatio())); // 赠品换算率
                    }
                    hxStorageOutDetailed.setPresentUnit(managePageContentDetailDTO.getPresentUnit()); // 赠品单位
                    hxStorageOutDetailed.setBasicPresentQuantity(BigDecimal.valueOf(managePageContentDetailDTO.getBasicPresentQuantity())); // 增品基本数量
                    hxStorageOutDetailed.setJibenNum(String.valueOf(managePageContentDetailDTO.getBasicQuantity())); // 基本数量
                    hxStorageOutDetailed.setJibenUnit(managePageContentDetailDTO.getBasicUnit()); // 基本单位
                    hxStorageOutDetailed.setGoodsSpecs(managePageContentDetailDTO.getItemSpec()); // 商品规格
                    hxStorageOutDetailed.setDetailedDate(managePageContentDetailDTO.getProducingDate()); // 生产日期
                    hxStorageOutDetailed.setPositionId(managePageContentDetailDTO.getStorageId()); // 库位id
                    hxStorageOutDetailed.setPositionNumber(managePageContentDetailDTO.getStorageName()); // 库位名称
                    hxStorageOutDetailed.setV2(managePageContentDetailDTO.getOutDate()); // 出库日期
                    hxStorageOutDetailed.setDaoqiDate(managePageContentDetailDTO.getExpireDate()); // 到期日期
                    hxStorageOutDetailed.setGoodsPcode69(managePageContentDetailDTO.getItemBarCode()); // 商品条码
                    hxStorageOutDetailed.setGoodsNumber(managePageContentDetailDTO.getItemCode()); // 商品代码
                    hxStorageOutDetailed.setGoodsId(managePageContentDetailDTO.getItemId()); // 商品id
                    String goodsName = managePageContentDetailDTO.getItemName(); // 商品名称

                    // 解决参数中的英文括号问题
                    if (goodsName != null && !goodsName.isEmpty()) {
                        goodsName = goodsName.replace("& #40;", "(");
                        goodsName = goodsName.replace("& #41;", ")");
                        hxStorageOutDetailed.setGoodsName(goodsName);
                    }

                    // 添加拣货单明细
                    hxStorageOutDetailedService.add(hxStorageOutDetailed);
                }
            }
        } catch (IOException e) {
            log.error("JSON 解析异常:", e);
            return ResponseData.error("请求处理时发生错误！");
        }
        return ResponseData.success(200,"添加成功",null);
    }

    /**
     * 审核新零帮出库单 测试方法
     */
    public ResponseData btnFinishXlb(ManageAuditVO manageAuditVO,HxStorageOut hxStorageOut) throws IOException {

        // 1、获取公司号，拿XLB的oauth2TOKEN
        BasicCustomer basicCustomerList = basicCustomerService.getById(hxStorageOut.getCustomerId());
        if (basicCustomerList == null) {
            return ResponseData.error("请维护公司号");
        }
        String gsnumber = basicCustomerList.getGsnumber();

        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setGsnumber(gsnumber);
        BasicXlbOauth2tokenResult bySpec = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
        String oauth2TokenXlb = bySpec.getOauth2TokenXlb();

        // 2、封装请求
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + oauth2TokenXlb);

        // 请求数据
        // 1.新零帮门店id
        String storeIdXlb = basicCustomerList.getStoreIdXlb();

        // 2.新零帮仓库id
        BasicWarehouse BasicWarehouseList = basicWarehouseService.getById(hxStorageOut.getSetWarehouseId());
        String warehouseXlbId = BasicWarehouseList.getWarehouseXlbId();

        manageAuditVO.setAdjustReasonName(hxStorageOut.getNotes());
        manageAuditVO.setClientId(hxStorageOut.getGetUnitId());
        manageAuditVO.setClientName(hxStorageOut.getGetUnit());
        manageAuditVO.setFid(hxStorageOut.getStorageNumber());
        manageAuditVO.setMemo(hxStorageOut.getNotes());
        String orderType = hxStorageOut.getOrderType(); // 单据名称
        String orderTypeXlb = "";
        if (orderType != null) {
            Map<String, String> orderTypeMap = new HashMap<>();
            orderTypeMap.put("门店调出","STORE_OUT");
            orderTypeMap.put("采购退货","RETURN");
            orderTypeMap.put("批发销售","WHOLESALE");
            orderTypeMap.put("调整出库","ADJUST_OUT");
            orderTypeMap.put("仓间调拨", "TRANSFER");
            orderTypeXlb = orderTypeMap.get(orderType);
        }
        manageAuditVO.setOrderType(orderTypeXlb);
        manageAuditVO.setStoreId(storeIdXlb);
        manageAuditVO.setStorehouseId(warehouseXlbId);

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonBody = objectMapper.writeValueAsString(manageAuditVO);

        log.info("审核请求参数:{}" , jsonBody);

        // 发送请求
        String post = HttpRequest.post(XLB_MANAGE_AUDIT)
                .header(headers)
                .body(jsonBody.toString()).execute().body();

        log.info("审核请求结果:{}" , post);

        ObjectMapper objectMapperPost = new ObjectMapper();
        JsonNode rootNode = objectMapperPost.readTree(post);
        String msg = rootNode.path("msg").asText();
        String code = rootNode.path("code").asText();
        String data = rootNode.path("data").asText();
        log.info("审核请求消息:{}" , msg);

        return ResponseData.success(Integer.valueOf(code),msg,data);
    }


    /**
     * 拉取新零帮出库单列表 正式方法
     *
     * @param hxStorageManageParams
     * @return
     */
    @Transactional(rollbackFor = Exception.class,propagation= Propagation.REQUIRED,timeout=120)
    @ResponseBody
    @RequestMapping("/pullXlbOutStorageManageListYYYYY")
    public ResponseData pullXlbOutStorageManageListYYYYY(HxStorageManageParams hxStorageManageParams) throws IOException {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();

        // 根据客户管理做出限制
        BasicCustomer one = basicCustomerService.lambdaQuery()
                .select(BasicCustomer::getId, BasicCustomer::getModeTms, BasicCustomer::getDeptId)
                .eq(BasicCustomer::getDeptId, deptId)
                .one();
        String modeTms = one.getModeTms();
        if (modeTms == null || !modeTms.equals("3")){
            return ResponseData.error("管理员设置不允许拉取！");
        }

        // 1、获取公司号，拿XLB的oauth2TOKEN
        BasicCustomer basicCustomerList = basicCustomerService.getById(hxStorageManageParams.getCustomerId());
        if (basicCustomerList == null) {
            return ResponseData.error("请维护公司号");
        }
        String gsnumber = basicCustomerList.getGsnumber();
        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setGsnumber(gsnumber);
        BasicXlbOauth2tokenResult bySpec = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
        String oauth2TokenXlb = bySpec.getOauth2TokenXlb();

        // 2、封装请求
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + oauth2TokenXlb);

        // 请求数据
        // 1.新零帮门店id
        String storeIdXlb = basicCustomerList.getStoreIdXlb();

        // 2.新零帮仓库id
        BasicWarehouse BasicWarehouseList = basicWarehouseService.getById(hxStorageManageParams.getSetWarehouseId());
        String warehouseXlbId = BasicWarehouseList.getWarehouseXlbId();

        // 3.创建时间
        List<String> createDate = new ArrayList<>();
        createDate.add(hxStorageManageParams.getModified_begin());
        createDate.add(hxStorageManageParams.getModified_end());

        // 4.客户号集合
        String getUnitId = hxStorageManageParams.getGetUnitId();
        String[] clientIdsArray = null;
        if (getUnitId != null){
            clientIdsArray = getUnitId.split(",");
            // 过滤掉空字符串
            clientIdsArray = Arrays.stream(clientIdsArray)
                    .filter(client -> !client.isEmpty())
                    .toArray(String[]::new);
        }

        // 5.订单类型
        String orderType = hxStorageManageParams.getOrderType();

        // 6.排序属性
        JSONArray ordersArray = new JSONArray();
        JSONObject orderObject = new JSONObject();
        orderObject.put("direction", "DESC");
        orderObject.put("property", "fid");
        // 将订单对象添加到订单数组中
        ordersArray.put(orderObject);

        // 7.分页
        String pageNumber = "0";
        String pageSize = "200";

        // 请求体
        JSONObject body = new JSONObject();
        body.put("store_id", storeIdXlb);
        body.put("storehouse_id", warehouseXlbId);
        body.put("client_ids", "[]");
        body.put("create_date", createDate);
        body.put("order_type", orderType);
        body.put("orders", ordersArray);
        body.put("page_number", pageNumber);
        body.put("page_size", pageSize);

        log.info("请求参数:{}" , body);

        // 发送请求
        String post = HttpRequest.post(XLB_MANAGE_PAGE)
                .header(headers)
                .body(body.toString()).execute().body();

        log.info("拣货单请求结果:{}" , post);

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            ManagePageDTO managePageDTO = objectMapper.readValue(post, ManagePageDTO.class);
            List<ManagePageContentDTO> content = managePageDTO.getData().getContent();

            for (ManagePageContentDTO managePageContentDTO : content) {
                String fid = managePageContentDTO.getFid();
                HxStorageOutParam hxStorageOut = new HxStorageOutParam();

                String memo = (managePageContentDTO.getAdjustReasonName() != null ? managePageContentDTO.getAdjustReasonName() : "") +
                        (managePageContentDTO.getMemo() != null ? managePageContentDTO.getMemo() : "") +
                        (managePageContentDTO.getSystemMemo() != null ? managePageContentDTO.getSystemMemo() : "");
                String notes = EmojiTransferUtil.emojiEncode(memo);
                hxStorageOut.setNotes(notes); // 调整原因

                // 共享属性
                hxStorageOut.setCustomerId(managePageContentDTO.getClientId()); // 收货客户id
                hxStorageOut.setCustomerName(managePageContentDTO.getClientName()); // 收货客户姓名
                hxStorageOut.setCreateUserName(managePageContentDTO.getCreateBy()); // 制单人
                hxStorageOut.setCreateTime(managePageContentDTO.getCreateTime()); // 制单时间
                hxStorageOut.setPeisongTime(managePageContentDTO.getDeliveryDate()); // 配送日
                hxStorageOut.setStorageNumber(fid); // 单据号
                hxStorageOut.setGoodsNum(String.valueOf(managePageContentDTO.getItemCount())); // 商品数量
                hxStorageOut.setOrderType(managePageContentDTO.getOrderTypeName()); // 单据类型名称
                hxStorageOut.setAssociationOrder(managePageContentDTO.getOutApplicationOrderFid()); // 关联出库单
                hxStorageOut.setGoodsNum(String.valueOf(managePageContentDTO.getQuantity())); // 商品数量
                hxStorageOut.setStorageState(managePageContentDTO.getStateName()); // 状态名称
                hxStorageOut.setGetUnitId(managePageContentDTO.getStoreId()); // 门店id
                hxStorageOut.setGetUnit(managePageContentDTO.getStoreName()); // 门店名称
                hxStorageOut.setSetWarehouseId(managePageContentDTO.getStorehouseId()); // 发货仓库id
                hxStorageOut.setSetWarehouse(managePageContentDTO.getStorehouseName()); // 仓库名称

                // 发送请求添加拣货单
                ResponseData responseData = this.addItem(hxStorageOut);
                if (!responseData.getSuccess()) {
                    return ResponseData.error("添加出库单失败！");
                }

                // 构造请求体，请求拣货单详情
                JSONObject bodyDetails = new JSONObject();
                bodyDetails.put("fid", fid);

                log.info("拣货单详情请求参数:{}" , bodyDetails);

                // 发送请求获取拣货单详情
                String postDetails = HttpRequest.post(XLB_MANAGE_READ)
                        .header(headers)
                        .body(bodyDetails.toString()).execute().body();

                log.info("拣货单详情请求结果:{}" , postDetails);

                // 解析拣货单详情
                ManageReadDetailDTO detailResDTO = objectMapper.readValue(postDetails, ManageReadDetailDTO.class);
                List<ManagePageContentDetailDTO> detailContent = detailResDTO.getData().getDetails();

                for (ManagePageContentDetailDTO managePageContentDetailDTO : detailContent) {
                    HxStorageOutDetailedParam hxStorageOutDetailed = new HxStorageOutDetailedParam();

                    // 共享属性
                    hxStorageOutDetailed.setStorageNumber(fid); // 拣货单号

                    // 设置其他属性
                    hxStorageOutDetailed.setUnit(managePageContentDetailDTO.getUnit()); // 单位
                    hxStorageOutDetailed.setNum(String.valueOf(managePageContentDetailDTO.getQuantity())); // 数量
                    hxStorageOutDetailed.setRate(String.valueOf(managePageContentDetailDTO.getRatio())); // 换算率
                    hxStorageOutDetailed.setPresentQuantity(BigDecimal.valueOf(managePageContentDetailDTO.getPresentQuantity())); // 赠送数量
                    hxStorageOutDetailed.setPresentRatio(BigDecimal.valueOf(managePageContentDetailDTO.getPresentRatio())); // 赠品换算率
                    hxStorageOutDetailed.setPresentUnit(managePageContentDetailDTO.getPresentUnit()); // 赠品单位
                    hxStorageOutDetailed.setBasicPresentQuantity(BigDecimal.valueOf(managePageContentDetailDTO.getBasicPresentQuantity())); // 增品基本数量
                    hxStorageOutDetailed.setJibenNum(String.valueOf(managePageContentDetailDTO.getBasicQuantity())); // 基本数量
                    hxStorageOutDetailed.setJibenUnit(managePageContentDetailDTO.getBasicUnit()); // 基本单位
                    hxStorageOutDetailed.setDaoqiDate(managePageContentDetailDTO.getExpireDate()); // 到期日期
                    hxStorageOutDetailed.setGoodsPcode69(managePageContentDetailDTO.getItemBarCode()); // 商品条码
                    hxStorageOutDetailed.setGoodsNumber(managePageContentDetailDTO.getItemCode()); // 商品代码
                    hxStorageOutDetailed.setGoodsId(managePageContentDetailDTO.getItemId()); // 商品id
                    String goodsName = managePageContentDetailDTO.getItemName(); // 商品名称

                    // 解决参数中的英文括号问题
                    if (goodsName != null && !goodsName.isEmpty()) {
                        goodsName = goodsName.replace("& #40;", "(");
                        goodsName = goodsName.replace("& #41;", ")");
                        hxStorageOutDetailed.setGoodsName(goodsName);
                    }

                    hxStorageOutDetailed.setGoodsSpecs(managePageContentDetailDTO.getItemSpec()); // 商品规格
                    hxStorageOutDetailed.setDetailedDate(managePageContentDetailDTO.getProducingDate()); // 生产日期
                    hxStorageOutDetailed.setPositionId(managePageContentDetailDTO.getStorageId()); // 库位id
                    hxStorageOutDetailed.setPositionNumber(managePageContentDetailDTO.getStorageName()); // 库位名称
                    hxStorageOutDetailed.setV2(managePageContentDetailDTO.getOutDate()); // 出库日期

                    // 添加拣货单明细
                    hxStorageOutDetailedService.add(hxStorageOutDetailed);
                }
            }
        } catch (IOException e) {
            log.error("JSON 解析异常:", e);
            return ResponseData.error("请求处理时发生错误！");
        }
        return ResponseData.success(200,"添加成功",null);
    }

    /**
     * 审核新零帮出库单 正式方法
     */
    public ResponseData btnFinishXlbYYYYYY(ManageAuditVO manageAuditVO,HxStorageOut hxStorageOut) throws IOException {

        // 1、获取公司号，拿XLB的oauth2TOKEN
        BasicCustomer basicCustomerList = basicCustomerService.getById(hxStorageOut.getCustomerId());
        if (basicCustomerList == null) {
            return ResponseData.error("请维护公司号");
        }
        String gsnumber = basicCustomerList.getGsnumber();

        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setGsnumber(gsnumber);
        BasicXlbOauth2tokenResult bySpec = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
        String oauth2TokenXlb = bySpec.getOauth2TokenXlb();

        // 2、封装请求
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + oauth2TokenXlb);

        // 请求数据
        // 1.新零帮门店id
        String storeIdXlb = basicCustomerList.getStoreIdXlb();

        // 2.新零帮仓库id
        BasicWarehouse BasicWarehouseList = basicWarehouseService.getById(hxStorageOut.getSetWarehouseId());
        String warehouseXlbId = BasicWarehouseList.getWarehouseXlbId();

        manageAuditVO.setAdjustReasonName(hxStorageOut.getNotes());
        manageAuditVO.setClientId(hxStorageOut.getGetUnitId());
        manageAuditVO.setClientName(hxStorageOut.getGetUnit());
        manageAuditVO.setFid(hxStorageOut.getStorageNumber());
        manageAuditVO.setMemo(hxStorageOut.getNotes());
        String orderType = hxStorageOut.getOrderType(); // 单据名称
        String orderTypeXlb = "";
        if (orderType != null) {
            Map<String, String> orderTypeMap = new HashMap<>();
            orderTypeMap.put("门店调出","STORE_OUT");
            orderTypeMap.put("采购退货","RETURN");
            orderTypeMap.put("批发销售","WHOLESALE");
            orderTypeMap.put("调整出库","ADJUST_OUT");
            orderTypeMap.put("仓间调拨", "TRANSFER");
            orderTypeXlb = orderTypeMap.get(orderType);
        }
        manageAuditVO.setOrderType(orderTypeXlb);
        manageAuditVO.setStoreId(storeIdXlb);
        manageAuditVO.setStorehouseId(warehouseXlbId);

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonBody = objectMapper.writeValueAsString(manageAuditVO);

        log.info("审核请求参数:{}" , jsonBody);

        // 发送请求
        String post = HttpRequest.post(XLB_MANAGE_AUDIT)
                .header(headers)
                .body(jsonBody.toString()).execute().body();

        log.info("审核请求结果:{}" , post);

        ObjectMapper objectMapperPost = new ObjectMapper();
        JsonNode rootNode = objectMapperPost.readTree(post);
        String msg = rootNode.path("msg").asText();
        log.info("审核请求消息:{}" , msg);

        return ResponseData.success(msg);
    }

    /***********************************************抽取方法************************************************************/

    /**
     * 获取部门前缀  ====> addStorage
     */
    public String getOperateIdOrderPrefix(User user) {
        if (user.getOperateId() != null) {
            Dept dept = new Dept();
            dept.setOperateId(user.getOperateId());
            Dept resdept = deptService.findBySpec(dept);
            if (resdept != null) {
                if (ToolUtil.isNotEmpty(resdept.getOrderPrefix())) {
                    return resdept.getOrderPrefix();
                } else {
                    return user.getAccount().substring(0, 3);
                }
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 添加出库单方法
     */
    public ResponseData addItem(HxStorageOutParam hxStorageOutParam){
        User user = userService.getcurrentUser();
        String trayCode = getOperateIdOrderPrefix(user);
        String storageNumber = null;
        if (ToolUtil.isNotEmpty(hxStorageOutParam.getStorageNumber())) {
            //校验客户单号 是否存在
            if (this.hxStorageOutService.checkCustomerStorage(hxStorageOutParam.getStorageNumber())) {
                return ResponseData.error("单号已存在");
            }
        } else {
            storageNumber = trayCode + "CK" + DateUtil.getDatesBch() + DateUtil.getRandomNumber();
            hxStorageOutParam.setStorageNumber(storageNumber);
        }

        hxStorageOutParam.setDeptId(user.getDeptId());
        hxStorageOutParam.setDeliverId(user.getDeliverId());
        hxStorageOutService.add(hxStorageOutParam);
        return ResponseData.success(hxStorageOutParam);
    }

    /**
     * 单位换算方法
     */
    private ConversionResult convertUnitsAndCheckStock(HxStorageOutDetailed detailed, Long goodsId, Long deptId) {
        // 1、获取商品信息
        HxBasicGoods rates = hxBasicGoodsService.getBaseMapper().selectOne(new QueryWrapper<HxBasicGoods>()
                .eq("id", goodsId)
                .eq("dept_id", deptId));
        if (rates == null) {
            throw new RuntimeException("商品ID:" + goodsId + " 的换算率未设置。");
        }

        // 2、计算出库数量
        String ckNum = detailed.getNum(); // 出库数量
        BigDecimal presentQuantity = detailed.getPresentQuantity(); // 出库赠送数量

        // BigDecimal对null处理
        BigDecimal newCkNum = (ckNum == null || ckNum.trim().isEmpty()) ? BigDecimal.ZERO : new BigDecimal(ckNum);
        BigDecimal presentNum = (presentQuantity == null || presentQuantity.equals(BigDecimal.ZERO)) ? BigDecimal.ZERO : presentQuantity;

        BigDecimal convertedNum = BigDecimal.ZERO; // 计算库存数量，一库位多数据原因

        // 3、换算单位
        String unit = detailed.getUnit(); // 单位
        String presentUnit = detailed.getPresentUnit(); // 赠送单位
        Map<String, BigDecimal> rateMap = new HashMap<>();
        rateMap.put(rates.getJibenUnit(), BigDecimal.ONE);
        rateMap.put(rates.getKcUnit(), new BigDecimal(rates.getKcRate()));
        rateMap.put(rates.getCgUnit(), new BigDecimal(rates.getCgRate()));
        rateMap.put(rates.getPfUnit(), new BigDecimal(rates.getPfRate()));
        rateMap.put(rates.getPsUnit(), new BigDecimal(rates.getPsRate()));

        if ( (!unit.isEmpty() && !rateMap.containsKey(unit)) || (!presentUnit.isEmpty() && !rateMap.containsKey(presentUnit)) ) {
            // Set 不重复集合
            Set<String> units = new HashSet<>();
            units.add(rates.getJibenUnit());
            units.add(rates.getKcUnit());
            units.add(rates.getCgUnit());
            units.add(rates.getPfUnit());
            units.add(rates.getPsUnit());

            // 将 Set 转换为 List
            List<String> unitsList = new ArrayList<>(units);

            // 构建错误消息
            StringBuilder unitsInfo = new StringBuilder();
            for (int i = 0; i < unitsList.size(); i++) {
                unitsInfo.append(unitsList.get(i));
                if (i < unitsList.size() - 1) {
                    unitsInfo.append(" ");
                }
            }

            throw new RuntimeException(
                    "未知的单位类型:" + unit + "，请检查单位类型是否正确。<br>" +
                            "正确单位为:" + "<strong><font color='red'>" + unitsInfo.toString() + "</font></strong>"
            );
        }
        BigDecimal num1 = BigDecimal.ZERO;
        BigDecimal num2 = BigDecimal.ZERO;
        if(!newCkNum.equals(BigDecimal.ZERO)){
            num1 = newCkNum.multiply(rateMap.get(unit)); // 计算基本数量(正品)
        }
        if (!presentNum.equals(BigDecimal.ZERO)){
            num2 = presentNum.multiply(rateMap.get(presentUnit)); // 计算基本数量(赠品)
        }
        convertedNum = num1.add(num2); // 总基本数量

        ConversionResult result = new ConversionResult(convertedNum, rates,num1,num2);
        return result;
    }

    /**
     * 验证库位库存
     */
    private ResponseData checkStock(HxStorageOutDetailed hxStorageOutDetailed, BigDecimal convertedNum, BigDecimal countNum, Long operateId, Long goodsId, Long deptId) {
        String positionNumber = hxStorageOutDetailed.getPositionNumber(); // 库位
        QueryWrapper<HxStorageStock> hxStorageStockQueryWrapper = new QueryWrapper<HxStorageStock>()
                .eq("position_number", positionNumber)
                .eq("goods_id", goodsId)
                .eq("operate_id", operateId)
                .eq("dept_id", deptId)
                .eq("detailed_date", hxStorageOutDetailed.getDetailedDate())
                .orderByDesc("jiben_num");
        List<HxStorageStock> hxStorageStocks =
                hxStorageStockService.getBaseMapper().selectList(hxStorageStockQueryWrapper);

        // 库位库存数量
        for (HxStorageStock hxStorageStock : hxStorageStocks) {
            BigDecimal jibenNum = hxStorageStock.getJibenNum();
            countNum = countNum.add(jibenNum);
        }

        // 判断 -- 出库基本数量 和 库位库存 对比
        if (countNum.compareTo(convertedNum) < 0) {
            return ResponseData.error("该日期库位库存不足");
        }

        // 5、更新极鹿库位库存
        for (HxStorageStock hxStorageStock : hxStorageStocks) {
            if (hxStorageStock.getJibenNum().compareTo(convertedNum) > 0) {
                // 减库存
                BigDecimal subtract = hxStorageStock.getJibenNum().subtract(convertedNum);
                hxStorageStock.setJibenNum(subtract);
                // 更新库存记录
                hxStorageStock.setV1("剩余数量:" + subtract + "删除:" + convertedNum);
                convertedNum = BigDecimal.ZERO;
                hxStorageStockService.updateById(hxStorageStock);
                break;
            } else if (hxStorageStock.getJibenNum().compareTo(convertedNum) == 0) {
                // 删除当前记录，执行下一个记录
                convertedNum = BigDecimal.ZERO;
                hxStorageStockService.removeById(hxStorageStock.getId());
                break;
            } else {
                // 如果不够，先扣除当前记录的全部数量
                convertedNum = convertedNum.subtract(hxStorageStock.getJibenNum());
                hxStorageStockService.removeById(hxStorageStock.getId());
            }
        }
        return ResponseData.success();
    }



//    @Transactional(rollbackFor = Exception.class)
//    @ResponseBody
//    @RequestMapping("/finish123123")
//    public ResponseData btnFinish123123(@RequestParam("ids") Long[] ids) {
//        if (ids == null || ids.length == 0){
//            return ResponseData.error("请选择订单");
//        }
//        try {
//            User user = userService.getcurrentUser();
//            Long operateId = user.getOperateId();
//            Long deptId = user.getDeptId();
//
//            for (Long id : ids) {
//                HxStorageOut hxStorageOut = hxStorageOutService.getById(id);
//                if ("审核".equals(hxStorageOut.getStorageState())) {
//                    return ResponseData.error("订单号:{}" , hxStorageOut.getStorageNumber() + " 已审核，请检查是否选择正确。");
//                }
//
//                // 1、根据id查询订单号，根据订单号获取拣货详情
//                String storageNumber = hxStorageOut.getStorageNumber();
//                QueryWrapper<HxStorageOutDetailed> storageNumberDetailed =
//                        new QueryWrapper<HxStorageOutDetailed>()
//                                .eq("storage_number", storageNumber);
//                List<HxStorageOutDetailed> hxStorageOutDetaileds =
//                        hxStorageOutDetailedService.getBaseMapper().selectList(storageNumberDetailed);
//                if (hxStorageOutDetaileds == null || hxStorageOutDetaileds.isEmpty()){
//                    return ResponseData.error("订单号:{}" , storageNumber + " 中不存在拣货详情，请检查是否选择正确。");
//                }
//                // 2.遍历拣货单详情，盘点库位库存，是否充足
//                for (HxStorageOutDetailed hxStorageOutDetailed : hxStorageOutDetaileds) {
//                    // 判断库位和数量不为空
//                    if (hxStorageOutDetailed.getNum() == null || hxStorageOutDetailed.getNum().trim().isEmpty() || hxStorageOutDetailed.getPositionNumber() == null || hxStorageOutDetailed.getPositionNumber().trim().isEmpty()) {
//                        return ResponseData.error("订单号:{}" , storageNumber + " 中存在明细数据未填写完整，请检查数量和库位是否已正确填写。");
//                    }
//                    Long goodsId = hxStorageOutDetailed.getGoodsId();
//
//                    // 3、换算单位
//                    ConversionResult conversionResult = convertUnitsAndCheckStock(hxStorageOutDetailed, goodsId, deptId);
//                    BigDecimal convertedNum = conversionResult.getConvertedNum();
//
//                    // 4、验证时间库位库存
//                    String positionNumber = hxStorageOutDetailed.getPositionNumber(); // 库位
//                    QueryWrapper<HxStorageStock> hxStorageStockQueryWrapper = new QueryWrapper<HxStorageStock>()
//                            .eq("position_number", positionNumber)
//                            .eq("goods_id", goodsId)
//                            .eq("operate_id", operateId)
//                            .eq("dept_id", deptId)
//                            .eq("detailed_date", hxStorageOutDetailed.getDetailedDate())
//                            .orderByDesc("jiben_num");
//                    List<HxStorageStock> hxStorageStocks =
//                            hxStorageStockService.getBaseMapper().selectList(hxStorageStockQueryWrapper);
//
//                    BigDecimal countNum = BigDecimal.ZERO; // 计算库位库存
//                    for (HxStorageStock hxStorageStock : hxStorageStocks) {
//                        BigDecimal jibenNum = hxStorageStock.getJibenNum();
//                        countNum = countNum.add(jibenNum);
//                    }
//
//                    // 判断 -- 出库基本数量 和 库位库存 对比
//                    if (countNum.compareTo(convertedNum) < 0) {
//                        return ResponseData.error("该日期库位库存不足");
//                    }
//
//                    // 5、更新库位库存
//                    for (HxStorageStock hxStorageStock : hxStorageStocks) {
//                        if (hxStorageStock.getJibenNum().compareTo(convertedNum) > 0) {
//                            // 减库存
//                            BigDecimal subtract = hxStorageStock.getJibenNum().subtract(convertedNum);
//                            hxStorageStock.setJibenNum(subtract);
//                            // 更新库存记录
//                            hxStorageStock.setV1("剩余数量:{}" , subtract + "删除:{}" , convertedNum);
//                            convertedNum = BigDecimal.ZERO;
//                            hxStorageStockService.updateById(hxStorageStock);
//                            break;
//                        } else if (hxStorageStock.getJibenNum().compareTo(convertedNum) == 0) {
//                            // 删除当前记录，执行下一个记录
//                            convertedNum = BigDecimal.ZERO;
//                            hxStorageStock.setV1("删除记录");
////                            hxStorageStockService.updateById(hxStorageStock);
//                            hxStorageStockService.removeById(hxStorageStock.getId());
//                            break;
//                        } else {
//                            // 如果不够，先扣除当前记录的全部数量
//                            convertedNum = convertedNum.subtract(hxStorageStock.getJibenNum());
//                            // 删除当前记录，执行下一个记录
//                            hxStorageStock.setV1("删除记录");
////                            hxStorageStockService.updateById(hxStorageStock);
//                            hxStorageStockService.removeById(hxStorageStock.getId());
//                        }
//                    }
//
//                    // 设置出库时间 暂用v2
//                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                    String outTime = dateFormat.format(new Date());
//                    hxStorageOutDetailed.setV2(outTime);
//                    hxStorageOutDetailedService.updateById(hxStorageOutDetailed);
//                }
//
//                // 6、根据id，修改状态为审核
//                if ("制单".equals(hxStorageOut.getStorageState())) {
//                    HxStorageOutParam param = new HxStorageOutParam();
//                    param.setStorageState("审核");
//                    param.setId(Integer.parseInt(id.toString()));
//                    hxStorageOutService.update(param);
//                }
//            }
//            return ResponseData.success(202, "审核成功", "");
//        } catch (Exception e) {
//            log.error("Error during finish operation: {}", e.getMessage(), e);
//            return ResponseData.error(e.getMessage());
//        }
//    }

}